package com.itstudy.controller;

import com.itstudy.pojo.Category;
import com.itstudy.pojo.Result;
import com.itstudy.service.CategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("category")
public class CategoryController {

    @Autowired
    private CategoryService categoryService;

    @PostMapping()
    public Result add(@RequestBody @Validated(Category.Add.class) Category category) {
        categoryService.add(category);
        return Result.success();
    }

    @GetMapping
    public Result get() {
        List<Category> list=categoryService.query();
        return Result.success(list);
    }

    @GetMapping("/detail")
    public Result getDetail(@RequestParam ("id") Integer id) {
        Category c=categoryService.findById(id);
        return Result.success(c);
    }

    @PutMapping
    public Result update(@RequestBody @Validated(value = Category.Update.class) Category category) {
        categoryService.update(category);
        return Result.success();
    }

    @DeleteMapping
    public Result delete(Integer id) {
        int i =categoryService.deleteById(id);
        if(i>0) {
            return Result.success();
        }
        return Result.error("刪除失敗");
    }
}
